<template>
  <div>
    <el-select
      v-model="currentValue"
      :multiple="multiple"
      :disabled="disabled"
      clearable
      filterable
      remote
      placeholder="请选择分类"
      :remote-method="remoteMethod"
      :loading="loading"
      @change="change"
    >
      <el-option v-for="item in optionList" :key="item.id" :label="item.displayName" :value="item.id">
        <span v-if="item.code.length/5 >= 2 && item.code.length/5 < 3">╰───</span>
        <span v-if="item.code.length/5 >= 3 && item.code.length/5 < 4" style="margin-left:40px;">╰───</span>
        <span v-if="item.code.length/5 >= 4 && item.code.length/5 < 5" style="margin-left:80px;">╰───</span>
        <span v-if="item.code.length/5 >= 5 && item.code.length/5 < 6" style="margin-left:120px;">╰───</span>
        {{ item.displayName }}
      </el-option>
    </el-select>
    <!-- <el-button slot="suffix" icon="el-icon-refresh" title="刷新"></el-button> -->
  </div>
</template>

<script>
import { getCategoriesWithCache } from "@/api/category";

export default {
  name: "CategorySelector",
  props: {
    moduleTypeId: {
      type: String,
      required: true
    },
    multiple: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: [Number, Array],
      default: undefined
    }
  },
  data() {
    return {
      currentValue: this.value,
      items: [],
      optionList: [],
      loading: false
    };
  },
  watch: {
    value(newValue) {
      this.currentValue = newValue;
    }
  },
  mounted() {
    this.load();
  },
  methods: {
    change(val) {
      this.$emit("input", val);
    },
    load() {
      this.getList(this.moduleTypeId);
    },
    remoteMethod(query) {
      if (query) {
        this.optionList = this.items.filter(item => {
          return item.displayName.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
      } else {
        this.optionList = this.items;
      }
    },
    getList(moduleTypeId) {
      this.loading = true;
      const q = {
        keyWords: undefined,
        moduleTypeId: moduleTypeId,
        isOnlyRoot: undefined,
        parentId: undefined
      };
      getCategoriesWithCache(q).then(result => {
        this.items = result;
        const rootList = this.items.filter(m => !m.parentId);
        this.buildoptionList(rootList);
        this.loading = false;
      });
    },
    buildoptionList(parentList) {
      parentList.forEach(m => {
        this.optionList.push(m);
        const nodes = this.items.filter(z => z.parentId === m.id);
        if (nodes.length > 0) {
          this.buildoptionList(nodes);
        }
      });
    }
  }
};
</script>
